import React, { useEffect, useState } from 'react'
import useGetTableData from '@/hooks/useGetTableData'
import { getProductColorPageList, getSpuOptions } from '@/api/goods'
import {
  periodConfigExportExcel,
  getPeriodConfigList,
  importPeriodConfig,
  periodConfigUpdateConfig,
  getReorderUnConfigNum,
} from '@/api/reorder'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useCycleColumns } from '../columns'
import { ReorderPeriodConfigVO } from '../types'
import CustomTable from '@/components/CustomTable'
import { SearchForm } from '@/components/CustomForm'
import './ReturnCycle.less'
import { Empty, message, Spin, Typography } from 'antd'
import useGetClassIds from '@/hooks/useGetClassIds'
import { ITableDataColor } from '@/pages/Goods/Style/types'
import PermissionButton from '@/components/PermissionButton'
import { ImportOutlined, UploadOutlined } from '@ant-design/icons'
import { exportNotification, importNotification } from '@/utils/util'
import { useNavigate } from 'react-router-dom'
import ImportFileModal from '@/components/ImportFileModal'
import { IMPORT_FILE_ENUM } from '@/constant'
import { useAppSelector } from '@/store/hooks'
import dayjs from 'dayjs'
const Index: React.FC = () => {
  let SpuTimeout: ITimeoutType
  let ColorTimeout: ITimeoutType
  const navigate = useNavigate()
  const [form] = useForm()
  const [FormUpload] = useForm()
  const [spinning, setspinning] = useState<boolean>(false)
  const [hasKnowTop, sethasKnowTop] = useState(true)
  const [isUploadFileShow, setisUploadFileShow] = useState<boolean>(false)
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const [SpuOptions, setSpuOptions] = useState<IOptionItem[]>([])
  const [ColorOptions, setColorOptions] = useState<IOptionItem[]>([])
  const [tableData, settableData] = useState<ReorderPeriodConfigVO[]>([])
  const [exportLoading, setexportLoading] = useState(false)
  const [unConfigInfo, setunConfigInfo] = useState<{ periodNum: number; minOrderNum: number }>({
    periodNum: 0,
    minOrderNum: 0,
  })
  const { classIdOptions, settinyClassIds, tinyClassIds, handleClassIdChange } = useGetClassIds()
  useEffect(() => {}, [])
  const { tableProps, params, setParams, search, reset } = useGetTableData<ReorderPeriodConfigVO>(getPeriodConfigList, {
    form: form,
    defaultFieldsParams: {},
    immediatelySend: false,
  })
  useEffect(() => {
    getNums()
    search({
      ...params,
    })
  }, [])
  useEffect(() => {
    settableData(tableProps.dataSource)
  }, [tableProps.dataSource])
  const getNums = async () => {
    const res = await getReorderUnConfigNum()
    if (res?.code === 200) {
      res?.data && setunConfigInfo(res.data)
    }
  }
  const reLoadPage = () => {
    search(params)
  }
  const handleSearchColor = (newValue = '') => {
    if (ColorTimeout) {
      clearTimeout(ColorTimeout)
      ColorTimeout = null
    }
    const getOptions = async () => {
      const res = await getProductColorPageList<ITableDataColor>({ colorGroupSearchName: newValue, enableStatus: 1 })
      if (res.code === 200) {
        const data =
          res?.data?.list?.map((item) => {
            return {
              label: item.colorDetailName,
              value: item.colorDetailName,
            }
          }) || []
        setColorOptions(data)
      }
    }
    ColorTimeout = setTimeout(getOptions, 500)
  }
  const handleSearchSpuOptions = (newValue = '') => {
    if (!newValue) return
    if (SpuTimeout) {
      clearTimeout(SpuTimeout)
      SpuTimeout = null
    }
    const getOptions = async () => {
      const res = await getSpuOptions<{
        spuName: string
        spuCode: string
        designCode: string
      }>({ keyword: newValue })
      if (res.code === 200) {
        const data =
          res?.data?.map((item) => {
            return {
              label: `${item?.spuCode}｜${item.spuName}${item?.designCode ? '｜' + item?.designCode : ''}`,
              value: item.spuCode,
            }
          }) || []
        setSpuOptions(data)
      }
    }
    SpuTimeout = setTimeout(getOptions, 500)
  }
  const onUploadFileCancel = () => {
    FormUpload.resetFields()
    setisUploadFileShow(false)
  }
  const onUploadFileOk = async () => {
    const { file } = await FormUpload.validateFields()
    setexportLoading(true)
    const res = await importPeriodConfig<{ linkUrl: string }>(file).finally(() => {
      setexportLoading(false)
      FormUpload.resetFields()
    })
    if (res.code === 200) {
      importNotification(res?.data?.linkUrl)
      search(params)
      onUploadFileCancel()
    }
  }
  const handleExport = async () => {
    setexportLoading(true)
    setspinning(true)
    const res = await periodConfigExportExcel({
      ...params,
    })
      .catch(() => setspinning(false))
      .finally(() => {
        setexportLoading(false)
      })
    if (res?.code === 200 && res?.data) {
      await exportNotification(res?.data, navigate).finally(() => setspinning(false))
    }
  }
  const onSave = async (info: ReorderPeriodConfigVO) => {
    const res = await periodConfigUpdateConfig(info).finally(() => {
      search(params)
    })
    if (res.code === 200) {
      message.success('操作成功')
    }
  }
  return (
    <PageContainer className="return_cycle_page">
      <div className="waittodo_box">
        <div className="wait_main">
          <div className="wm_item">
            <div className="wm_item_title">未维护返单周期</div>
            <div className="wm_item_num">
              <Typography.Link
                underline
                onClick={() => {
                  form.resetFields()
                  form.setFieldsValue({
                    periodFlag: 0,
                  })
                  search({
                    current: 1,
                    size: 10,
                    spuSearchInfo: null,
                    tinyClassIds: null,
                    colorSearchInfo: null,
                    periodFlag: 0,
                    minOrderFlag: null,
                  })
                }}
              >
                {unConfigInfo?.periodNum || 0}条
              </Typography.Link>
            </div>
          </div>
          <div className="wm_item">
            <div className="wm_item_title">未维护起订量</div>
            <div className="wm_item_num">
              <Typography.Link
                underline
                onClick={() => {
                  form.resetFields()
                  form.setFieldsValue({
                    minOrderFlag: 0,
                  })
                  search({
                    current: 1,
                    size: 10,
                    spuSearchInfo: null,
                    tinyClassIds: null,
                    colorSearchInfo: null,
                    periodFlag: null,
                    minOrderFlag: 0,
                  })
                }}
              >
                {unConfigInfo?.minOrderNum || 0}条
              </Typography.Link>
            </div>
          </div>
        </div>
      </div>
      <SearchForm
        className="return_cycle"
        params={params}
        form={form}
        searchConfig={[
          {
            name: 'productYear',
            label: '年份',
            type: 'DatePicker',
            placeholder: '请选择年份',
            config: {
              picker: 'year',
              format: 'YYYY',
            },
          },
          {
            label: 'SPU商品',
            name: 'spuSearchInfo',
            type: 'Select',
            option: SpuOptions,
            placeholder: '款式编码/款式名称/助记码',
            config: {
              suffixIcon: null,
              showSearch: true,
              filterOption: false,
              optionFilterProp: 'label',
              onSearch: handleSearchSpuOptions,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
            },
          },
          {
            name: 'tinyClassIds',
            label: '款式分类',
            type: 'Cascader',
            option: classIdOptions,
            placeholder: '请选择款式分类',
            config: {
              changeOnSelect: true,
              onChange: handleClassIdChange,
              onClear: () => settinyClassIds([]),
              fieldNames: { label: 'className', value: 'classConfigId', children: 'childrenList' },
            },
          },
          {
            name: 'colorSearchInfo',
            label: '款式色',
            type: 'Select',
            option: ColorOptions,
            placeholder: '请选择款式色',
            config: {
              suffixIcon: null,
              showSearch: true,
              filterOption: false,
              optionFilterProp: 'label',
              onSearch: handleSearchColor,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
            },
          },
          {
            name: 'minOrderFlag',
            label: '是否维护起订量',
            type: 'Select',
            option: [
              { label: '是', value: 1 },
              { label: '否', value: 0 },
            ],
          },
          {
            name: 'periodFlag',
            label: '是否维护返单周期',
            type: 'Select',
            option: [
              { label: '是', value: 1 },
              { label: '否', value: 0 },
            ],
          },
        ]}
        onFinish={(vals: any) => {
          search({
            ...vals,
            tinyClassIds: tinyClassIds.length > 0 ? tinyClassIds : null,
            productYear: vals.productYear ? dayjs(vals.productYear).format('YYYY') : null,
          })
        }}
        onReset={() => {
          settinyClassIds([])
          reset()
        }}
        extra={
          <div className="table_extra_flex_wrapbox">
            <div className="table_extra_flex">
              <PermissionButton
                icon={<ImportOutlined />}
                permission="cycleBatchImport"
                onClick={() => setisUploadFileShow(true)}
              >
                批量导入配置
              </PermissionButton>
            </div>
            <div className="table_extra_flex">
              <PermissionButton
                permission="cycleExport"
                icon={<UploadOutlined />}
                loading={exportLoading}
                onClick={handleExport}
              >
                导出
              </PermissionButton>
            </div>
          </div>
        }
      ></SearchForm>
      <CustomTable
        className="small_sise_customtable"
        bordered
        columns={useCycleColumns({
          tableData,
          settableData,
          onSave,
          reLoadPage,
          canEdit: buttonCodeList?.includes('cycleBatchImport'),
        })}
        {...tableProps}
        rowKey={(rows) => rows.id}
        extraHeight={100}
        isScrollY
        filterDomClassName={'return_cycle'}
      />
      <ImportFileModal
        loading={exportLoading}
        open={isUploadFileShow}
        onCancel={onUploadFileCancel}
        onOk={onUploadFileOk}
        form={FormUpload}
        tempCode={IMPORT_FILE_ENUM.RETURNCYCLE_IMPORT}
      ></ImportFileModal>
      <Spin spinning={spinning} fullscreen />
    </PageContainer>
  )
}

export default Index
